package concurrent.c_006_Lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 还可以指定为公平锁
 * * 公平锁：按照线程在队列中的排队顺序，先到者先拿到锁
 * * 非公平锁：当线程要获取锁时，无视队列顺序直接去抢锁，谁抢到就是谁的
 */
public class T05_ReentrantLock5 extends Thread {
    // 参数为 true 表示为公平锁，请对比输出结果
    private static ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        T05_ReentrantLock5 rl = new T05_ReentrantLock5();
        Thread th1 = new Thread(rl);
        Thread th2 = new Thread(rl);
        th1.start();
        th2.start();
    }
}